<template>
  <div class="provincial-distribution-container">
    <div class="chart-header">
      <h3 class="chart-title">省级地域分布</h3>
      <div class="date-navigation">
        <i class="el-icon-arrow-left date-arrow" :class="{ 'disabled': !canGoPrev }" @click="prevDate"></i>
        <span class="date-text">{{ currentDate }}</span>
        <i class="el-icon-arrow-right date-arrow" :class="{ 'disabled': !canGoNext }" @click="nextDate"></i>
      </div>
    </div>

    <div class="chart-content">
      <div class="map-section">
        <div ref="mapContainer" class="map-container"></div>
        <!-- <div class="map-legend">
          <div class="legend-title">访问人数</div>
          <div class="legend-bar">
            <div class="legend-gradient"></div>
            <div class="legend-labels">
              <span class="legend-min">1</span>
              <span class="legend-max">1,000</span>
            </div>
          </div>
        </div> -->
      </div>

      <div class="table-section">
        <el-table :data="tableData" style="width: 100%" stripe>
          <el-table-column prop="province" label="省份" min-width="120" sortable="custom">
          </el-table-column>
          <el-table-column prop="visitorCount" label="访问人数" sortable="custom" min-width="120">
            <template slot="header">
              <span>访问人数</span>
              <!-- <i class="el-icon-arrow-down sort-icon"></i>
              <span class="sort-number">1</span> -->
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="占比" sortable="custom" min-width="100">
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import '@/utils/china'
import { getProvinceRegionDistribution } from '@/api/chenlong.js'
export default {
  name: 'ProvincialDistribution',
  props: {
    corpId: {
      type: String,
      default: ''
    },
    dateRange: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentDate: '',
      currentPickDate: new Date(),
      chart: null,
      selectedProvince: null,
      tableData: [
        { province: '河南', visitorCount: 1000, percentage: '80.90%' },
        { province: '广东', visitorCount: 27, percentage: '2.18%' },
        { province: '北京', visitorCount: 20, percentage: '1.61%' },
        { province: '江苏', visitorCount: 19, percentage: '1.53%' },
        { province: '山西', visitorCount: 17, percentage: '1.37%' },
        { province: '山东', visitorCount: 15, percentage: '1.21%' },
        { province: '河北', visitorCount: 12, percentage: '0.97%' },
        { province: '浙江', visitorCount: 10, percentage: '0.81%' },
        { province: '四川', visitorCount: 8, percentage: '0.65%' },
        { province: '湖北', visitorCount: 6, percentage: '0.48%' }
      ],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 34
      }
    }
  },
  watch: {
    corpId: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.loadData()
        }
      }
    },
    dateRange: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          if (newVal && newVal.length > 0) {
            const lastDay = new Date(newVal[1])
            this.currentPickDate = lastDay
            this.currentDate = this.formatDateDisplay(this.currentPickDate)
          }
          this.loadData()
        }
      }
    }
  },
  computed: {
    // 日期切换判断逻辑
    canGoPrev() {
      // 判断是否可以点击左箭头（前一天）- 可以点击过去时间
      if (!this.currentPickDate) return false
      // 左箭头总是可以点击，因为可以查看过去的数据
      return true
    },
    canGoNext() {
      // 判断是否可以点击右箭头（后一天）- 不能点击未来时间
      if (!this.currentPickDate) return false
      const today = new Date()
      today.setHours(23, 59, 59, 999)
      const nextDate = new Date(this.currentPickDate)
      nextDate.setDate(nextDate.getDate() + 1)
      return nextDate <= today
    }
  },
  created() {
    this.loadData()
  },
  mounted() {
    if (this.dateRange && this.dateRange.length > 0) {
      const lastDay = new Date(this.dateRange[1])
      this.currentPickDate = lastDay
      this.currentDate = this.formatDateDisplay(this.currentPickDate)
    } else {
      this.currentDate = this.formatDateDisplay(this.currentPickDate)
    }
    this.initMap()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    updateCurrentDate() {
      if (this.dateRange && this.dateRange.length > 0) {
        const endDate = new Date(this.dateRange[1])
        this.currentDate = this.formatDateDisplay(endDate)
      } else {
        this.currentDate = this.formatDateDisplay(new Date())
      }
    },
    formatDateForApi(date) {
      // 格式化日期为API需要的格式
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
    },
    formatDateDisplay(date) {
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const weekday = weekdays[date.getDay()]
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${weekday} ${year}/${month}/${day}`
    },
    async loadData() {
      // 根据corpId和当前选择的日期获取数据
      // console.log('Loading provincial data with corpId:', this.corpId, 'currentPickDate:', this.currentPickDate)
      // 这里可以调用API获取数据
      const params = {
        corpId: this.corpId || '',
        startTime: this.formatDateForApi(this.currentPickDate),
        endTime: this.formatDateForApi(this.currentPickDate)
      }
      //const res = await getProvinceRegionDistribution(params)
     // if (res.code == 200) {
        // this.tableData = res.data.list || []
        // this.pagination.total = res.data.total || 0
    //  }
    //  console.log(">>>", params,res);
    },
    initMap() {
      this.chart = echarts.init(this.$refs.mapContainer)

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            if (params.data) {
              return `${params.name}<br/>访问人数: ${params.data.value}人`
            }
            return `${params.name}<br/>访问人数: 0人`
          }
        },
        visualMap: {
          min: 1,
          max: 1000,
          left: 'left',
          top: 'bottom',
          text: ['高', '低'],
          calculable: true,
          inRange: {
            color: ['#e6f7ff', '#52c41a']
          },
          show: false
        },
        geo: {
          map: 'china',
          roam: false,
          scaleLimit: {
            min: 1,
            max: 2
          },
          zoom: 1.2,
          top: 50,
          left: 50,
          right: 50,
          bottom: 50,
          itemStyle: {
            normal: {
              areaColor: '#f0f0f0',
              borderColor: '#999',
              borderWidth: 1
            },
            emphasis: {
              areaColor: '#74b9ff',
              borderColor: '#0984e3',
              borderWidth: 3,
              shadowColor: 'rgba(116, 185, 255, 0.5)',
              shadowBlur: 10
            }
          },
          label: {
            normal: {
              show: true,
              fontSize: 14,
              color: '#000000',
              fontWeight: 'bold',
              textShadowColor: '#ffffff',
              textShadowBlur: 2,
              textShadowOffsetX: 1,
              textShadowOffsetY: 1
            },
            emphasis: {
              show: true,
              fontSize: 16,
              color: '#000000',
              fontWeight: 'bold',
              textShadowColor: '#ffffff',
              textShadowBlur: 3,
              textShadowOffsetX: 1,
              textShadowOffsetY: 1
            }
          }
        },
        series: [
          {
            name: '访问人数',
            type: 'map',
            map: 'china',
            geoIndex: 0,
            itemStyle: {
              normal: {
                areaColor: '#f0f0f0',
                borderColor: '#999',
                borderWidth: 1
              },
              emphasis: {
                areaColor: '#74b9ff',
                borderColor: '#0984e3',
                borderWidth: 3,
                shadowColor: 'rgba(116, 185, 255, 0.5)',
                shadowBlur: 10
              }
            },
            data: [
              { name: '河南', value: 1000 },
              { name: '广东', value: 27 },
              { name: '北京', value: 20 },
              { name: '江苏', value: 19 },
              { name: '山西', value: 17 },
              { name: '山东', value: 15 },
              { name: '河北', value: 12 },
              { name: '浙江', value: 10 },
              { name: '四川', value: 8 },
              { name: '湖北', value: 6 },
              { name: '湖南', value: 5 },
              { name: '安徽', value: 4 },
              { name: '福建', value: 3 },
              { name: '江西', value: 2 },
              { name: '辽宁', value: 1 }
            ]
          }
        ]
      }

      this.chart.setOption(option)

      // 添加点击事件
      this.chart.on('click', this.handleMapClick)

      // 响应式处理
      window.addEventListener('resize', this.handleResize)
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },

    prevDate() {
      // 实现日期向前切换逻辑
      if (!this.canGoPrev) return
      const newDate = new Date(this.currentPickDate)
      newDate.setDate(newDate.getDate() - 1) // 左箭头是前一天
      newDate.setHours(0, 0, 0, 0) // 确保设置为当天的开始时间
      this.currentPickDate = newDate
      this.updateDataByDate()
    },

    nextDate() {
      // 实现日期向后切换逻辑
      if (!this.canGoNext) return
      const newDate = new Date(this.currentPickDate)
      newDate.setDate(newDate.getDate() + 1) // 右箭头是后一天
      newDate.setHours(0, 0, 0, 0) // 确保设置为当天的开始时间
      this.currentPickDate = newDate
      this.updateDataByDate()
    },

    async updateDataByDate() {
      // 根据选择的日期更新数据
      this.currentDate = this.formatDateDisplay(this.currentPickDate)
      await this.loadData()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
    },

    handleMapClick(params) {
      if (params.componentType === 'series') {
        this.selectedProvince = params.name
        this.updateMapSelection()
      }
    },

    updateMapSelection() {
      if (!this.chart) return

      const option = this.chart.getOption()
      const seriesData = option.series[0].data

      // 更新数据，为选中的省份添加特殊标记
      const updatedData = seriesData.map(item => {
        if (item.name === this.selectedProvince) {
          return {
            ...item,
            itemStyle: {
              areaColor: '#2d3436',
              borderColor: '#0984e3',
              borderWidth: 3,
              shadowColor: 'rgba(9, 132, 227, 0.6)',
              shadowBlur: 15
            }
          }
        }
        return item
      })

      this.chart.setOption({
        series: [{
          data: updatedData
        }]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.provincial-distribution-container {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  position: relative;
}

.chart-title {
  font-size: 18px;
  font-weight: 600;
  color: #333333;
  margin: 0;
}

.date-navigation {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666666;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.date-arrow {
  cursor: pointer;
  font-size: 16px;
  color: #999999;
  transition: color 0.3s;

  &:hover {
    color: #409eff;
  }

  &.disabled {
    color: #c0c4cc;
    cursor: not-allowed;

    &:hover {
      color: #c0c4cc;
    }
  }
}

.date-text {
  font-size: 14px;
  color: #666666;
  min-width: 120px;
  text-align: center;
}

.chart-content {
  display: flex;
  gap: 20px;
  height: calc(100% - 60px);
}

.map-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.map-container {
  flex: 1;
  min-height: 400px;
}

.map-legend {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.legend-title {
  font-size: 12px;
  color: #666666;
}

.legend-bar {
  position: relative;
  width: 100px;
  height: 20px;
}

.legend-gradient {
  width: 100%;
  height: 100%;
  background: linear-gradient(to right, #e6f7ff, #52c41a);
  border-radius: 2px;
}

.legend-labels {
  position: absolute;
  top: -20px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  font-size: 10px;
  color: #666666;
}

.table-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.sort-icon {
  color: #52c41a;
  margin-left: 4px;
}

.sort-number {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #52c41a;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 16px;
  font-size: 10px;
  margin-left: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

// 响应式设计
@media (max-width: 1200px) {
  .chart-content {
    flex-direction: column;
    gap: 16px;
  }

  .map-container {
    min-height: 300px;
  }
}

@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    gap: 12px;
  }

  .date-navigation {
    position: static;
    transform: none;
  }
}
</style>
